package org.frv.wispr.business;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository @Transactional
public class AccountRepositoryHibernateImpl implements AccountRepository {
	private SessionFactory sessionFactory;
	
	public Account findById(long id) {
		return (Account) sessionFactory.getCurrentSession().get(Account.class, id);
	}

    public Account findByName(String name) {
        return (Account) sessionFactory.getCurrentSession()
                .createQuery("from Account where name=?")
                .setString(0, name)
                .uniqueResult();
    }


    public void save(Account account) {
		sessionFactory.getCurrentSession().save(account);
	}

    public void saveAccountAs(Account account, AccountTypeEnum accountType) {
        // throw a runtime exception when we try to save a non null parent account
        Session session = sessionFactory.getCurrentSession();
        AccountType type = (AccountType) session.createQuery("from AccountType where type=?")
                .setString(0, accountType.getTypeName())
                .uniqueResult();
        account.setAccountType(type);
        session.saveOrUpdate(account);
    }

    // we need to throw some runtime exceptions here if there is invalid information
    public void addEntry(AccountEntry entry, AccountEntry doubleEntry) {
        if (doubleEntry == null) {
            throw new InvalidEntryException("Double entry need to be defined");
        }
        // do we need to do all these checks here, or should we implement this on the
        // db level
        if (entry.getDoubleEntry() == null) {
            throw new InvalidEntryException("No double entry defined");
        }
        
    }

    public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Required
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
